const aesfn = require('./aesfn');
const mongo = require('mongodb');
const config = require('../config');
const MongoClient = mongo.MongoClient;
const DB_CONN_STR = config.dbUrl;
const getTime = function(date){
    return date.getFullYear()+'/'+(date.getMonth()+1)+'/'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds();
};

const articleOperate = {
    getAllArticle: function(whereStr) {
        const promise = new Promise(function(resolve, reject) {
            MongoClient.connect(DB_CONN_STR, function(err, db) {
                db.collection(config.articlesTable, function(err, collection) {
                    collection.find(whereStr).sort({"publishTime":-1}).toArray(function(err, docs) {
                        db.close();
                        if (!err) {
                            docs.forEach(function(val) {
                                val._id = aesfn.aesEncrypt(val._id.toString());
                                val.publishTime = getTime(val.publishTime);
                            })
                            resolve(docs);
                        } else {
                            reject(false);
                        }
                    });
                });
            });
        });
        return promise;
    },
    getSomeArticle: function(whereStr) {
        const promise = new Promise(function(resolve, reject) {
            try{
                if(whereStr._id){
                    whereStr._id = mongo.ObjectId(aesfn.aesDecrypt(whereStr._id));
                } 
            }catch(e){
                reject(false);
                return false;
            }
            MongoClient.connect(DB_CONN_STR, function(err, db) {
                db.collection(config.articlesTable, function(err, collection) {
                    collection.find(whereStr).toArray(function(err, docs) {
                        if (!err) {
                            if(docs.length<1){
                                reject(false);
                                return false;
                            }
                            docs.forEach(function(val) {
                                val._id = aesfn.aesEncrypt(val._id.toString());
                                val.publishTime = getTime(val.publishTime);
                            })
                            collection.update(whereStr, {"$inc":{"readingAmount":1}},function(err, result) {
                                if (!err) {
                                    //console.log(whereStr._id + ' += 1');
                                } else {
                                    //console.log(whereStr._id + ' ++ error');
                                }
                            });
                            db.close();
                            resolve(docs);
                        } else {
                            reject(false);
                        }
                    });
                });
            });
        });
        return promise;
    },
    getArticleCategories: function() {
        const promise = new Promise(function(resolve, reject) {
            MongoClient.connect(DB_CONN_STR, function(err, db) {
                db.collection(config.articlesTable, function(err, collection) {
                    collection.find().toArray(function(err, docs) {
                        if (!err) {
                            let categories=[];
                            /*
                            categories=[{
                                tag:'html',
                                articles[{
                                    link:'http://www.baidu.com',
                                    title:'这是第一篇博客',
                                    time:'2017-81'
                                },{
                                    link:'http://www.baidu.com',
                                    title:'这是第一篇博客',
                                    time:'2017-81'
                                }]
                            }]
                            */
                            docs.forEach(function(article) {
                                article.tags.forEach(function(articleTage){
                                    let flage=false;
                                    categories.forEach(function(item){
                                        if(articleTage===item.tag){
                                            item.articles.unshift({
                                                id:aesfn.aesEncrypt(article._id.toString()),
                                                title:article.title,
                                                readingAmount:article.readingAmount,
                                                publishTime: getTime(article.publishTime)
                                            });
                                            flage=true;
                                        }
                                    });
                                    if(!flage){
                                        categories.unshift({
                                            tag:articleTage,
                                            articles:[{
                                                id:aesfn.aesEncrypt(article._id.toString()),
                                                title:article.title,
                                                readingAmount:article.readingAmount,
                                                publishTime: getTime(article.publishTime)
                                            }]
                                        });
                                    }
                                })
                            });
                            db.close();
                            resolve(categories);
                        } else {
                            reject(false);
                        }
                    });
                });
            });
        });
        return promise;
    },

    getAboutme: function() {
        const promise = new Promise(function(resolve, reject) {
            MongoClient.connect(DB_CONN_STR, function(err, db) {
                db.collection(config.adminTable, function(err, collection) {
                    collection.find({'key':'admin'}).toArray(function(err, docs) {
                        if (!err) {
                            if(docs.length<1){
                                reject(false);
                                return false;
                            }
                            db.close();
                            resolve(docs[0]);
                        } else {
                            reject(false);
                        }
                    });
                });
            });
        });
        return promise;
    }
}

module.exports = articleOperate;